package com.tang.state;

import com.tang.bean.WaterSensor;
import com.tang.functions.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.scala.typeutils.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * 针对每种传感器输出最高的3个水位值
 *
 * @author tang
 * @since 2023/7/11 11:00
 */
public class KeyedListStateDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        env.setParallelism(1);

        env.socketTextStream("192.168.70.141", 7777)
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs() * 1000L)
                ).keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    // 1. 定义ListState
                    private ListState<Integer> listState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        // 2. 在Open方法中初始化状态
                        listState = getRuntimeContext().getListState(new ListStateDescriptor<>("listState", Types.INT()));
                    }

                    @Override
                    public void processElement(WaterSensor waterSensor,
                                               KeyedProcessFunction<String, WaterSensor, String>.Context ctx,
                                               Collector<String> out) throws Exception {
                        listState.add(waterSensor.getVc());

                        Iterable<Integer> vcListIt = listState.get();
                        List<Integer> vcList = new ArrayList<>();
                        for (Integer vc : vcListIt) {
                            vcList.add(vc);
                        }
                        vcList.sort((o1, o2) -> o2 - o1);
                        if (vcList.size() > 3) {
                            vcList.remove(3);
                        }

                        out.collect("传感器ID为" + waterSensor.getId() + ", 最大的3个水位值 = " + vcList);

                        listState.update(vcList);
//                                listState.get();            //取出 list状态 本组的数据，是一个Iterable
//                                listState.add();            // 向 list状态 本组 添加一个元素
//                                listState.addAll();         // 向 list状态 本组 添加多个元素
//                                listState.update();         // 更新 list状态 本组数据（覆盖）
//                                listState.clear();          // 清空List状态 本组数据
                    }

                }).print();

        env.execute();
    }

}
